package com.jh.paymentchannel.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConstants;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.jh.paymentchannel.util.PaymentChannelConstants;
import com.jh.paymentchannel.util.Util;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝APP支付
 */
@Service
public class AlipayAppPayTopupRequest implements TopupRequest {

    //TODO
	private static final Logger log = LoggerFactory.getLogger(AlipayAppPayTopupRequest.class);

    @Value("${alipay.appId}")
	private String appId;

    @Value("${alipay.privateKey}")
    private String privateKey;

    @Value("${alipay.alipayPubKey}")
    private String publicKey;

    @Autowired
    private Util util;

	@Override
	public Map<String, String> topupRequest(HttpServletRequest request, String amount,
			String ordercode, String orderdesc, String extra, String notifyurl,
			String returnurl, String channelparam) throws UnsupportedEncodingException {
		// TODO Auto-generated method stub
        log.info("支付宝App支付，生成订单处理开始");

        Map<String, String> map = new HashMap<String, String>();
        RestTemplate restTemplate = new RestTemplate();
        URI uri = util.getServiceUrl("transactionclear", "error url request!");
        String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("order_code", ordercode);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        log.info("查询订单信息结果result={}" + result);
        JSONObject jsonObject;
        JSONObject resultObj;

        try {
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
        } catch (Exception e) {
            log.error("查询订单信息出错");
            map.put("resp_code", "failed");
            map.put("channel_type", "milian");
            map.put("resp_message", "没有该订单信息");
            return map;
        }

        String userid = resultObj.getString("userid");
        // 费率
        String rate = resultObj.getString("rate");
        // 额外费率
        String extraFee = resultObj.getString("extraFee");
        // 银行卡
        String bankCard = resultObj.getString("bankcard");


        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                appId  ,
                privateKey,
                "json",
                AlipayConstants.CHARSET_UTF8,
                publicKey,
                "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest aliPayRequest = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(orderdesc);
        model.setSubject("App支付");
        model.setOutTradeNo(ordercode);
        model.setTimeoutExpress("30m");
        model.setTotalAmount(amount);
        model.setProductCode("QUICK_MSECURITY_PAY");
        aliPayRequest.setBizModel(model);
        if (!StringUtils.isEmpty(notifyurl)) {
            aliPayRequest.setNotifyUrl(notifyurl);
        }

        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse tradeAppPayResponse = alipayClient.sdkExecute(aliPayRequest);
            String resBody = tradeAppPayResponse.getBody();

            //jsonObject = JSONObject.fromObject(resBody);
            //JSONObject.toBean()
            map.put("resp_code", "success");
            map.put("channel_type", PaymentChannelConstants.CHANNEL_ALIPAY_APP_PAY);
            //map.put("resp_code", "success");
            //map.put("channel_type", "alipay");
            //map.put("code_url", codeURL);
            map.put("body", resBody);

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }


        return map;



	}

}
